package com.ndky.annotation.reflect.three;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 执行方法和设置属性
 * author: 核桃
 * date: 2023/11/16
 **/
public class TestThree {

    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException, NoSuchFieldException {

        // 获取反射对象
        Class userClass = Class.forName("com.ndky.annotation.reflect.three.UserThree");

        // 通过 Class 对象构造其真实类 User 的对象
        UserThree userThree = (UserThree) userClass.newInstance();

        Method setName = userClass.getDeclaredMethod("setName", String.class);
        // 执行方法
        setName.invoke(userThree, "zhangsan");

        System.out.println(userThree.getName());
        System.out.println("=====================");

        // 获取属性
        Field age = userClass.getDeclaredField("age");
        // 必须! 设置属性可被修改
        age.setAccessible(true);
        // 设置属性
        age.set(userThree, 18);
        System.out.println(userThree.getAge());
    }
}
